var isLoadingAllData = true;//标识当前是不是在加载全部数据
var isClickExportBtn = false;//标识当前是不是点击了导出按钮
//请求全部数据
$.ajax({
    method: 'POST',
    url: '/csfy/user/findAllUamsUser.do',
    success: function (res) {
        isLoadingAllData = false
        if (res && res.code && res.code == 200) {
            dataList = res.rows
            if(isClickExportBtn) {
                flag = true
                isClickExportBtn = false
                $("#fountainTextG").show()
                setTimeout(() => {
                    exportCouponExcel(dataList)
                }, 0)
                handleLoading()
            }
        }
    },
    error: function (err) {
        isLoadingAllData = false
    }
})

//总条目
var total = 0;
//总数据列表
var dataList = null;
var exportTimer = null;
function handleLoading() {
    exportTimer && window.clearInterval(exportTimer)
    exportTimer = null
    exportTimer = setInterval(() => {
        if (window.sessionStorage.getItem('exportFinished')) {
        flag = false
        $("#fountainTextG").hide()
        window.sessionStorage.removeItem('exportFinished')
        exportTimer && window.clearInterval(exportTimer)
        exportTimer = null
        isClickExportBtn = false
    }
}, 1000)
}
 var flag = false

//退出登录
function logout() {
    $.ajax({
        url: '/csfy/dologout.do',
        method: 'POST',
        success: function (res) {
            if (JSON.parse(res).code == 200) {
                window.location.href = "/csfy/index.do"
            }
        }
    })
}

$("body").click(function () {
    $("#id-card-photo-wrapper").hide(300);
    angle = 0;
    $("#id-card-photo").rotate(0);
})

Date.prototype.pattern = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    var week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : '') + week[this.getDay() + '']);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(('' + o[k]).length)));
        }
    }
    return fmt;
}

//根据窗口调整表格高度
$(window).resize(function () {
    $('#mytab').bootstrapTable('resetView', {
        height: tableHeight()
    })
})

//生成用户数据
$('#mytab').bootstrapTable({
    method: 'POST',
    contentType: "application/x-www-form-urlencoded",//必须要有！！！！
    url: "/csfy/user/findAllUamsUser.do",//要请求数据的文件路径
    height: tableHeight(),//高度调整
    toolbar: '#toolbar',//指定工具栏
    striped: true, //是否显示行间隔色
    dataField: "rows",//bootstrap table 可以前端分页也可以后端分页，这里
    //我们使用的是后端分页，后端分页时需返回含有total：总记录数,这个键值好像是固定的
    //rows： 记录集合 键值可以修改  dataField 自己定义成自己想要的就好
    pageNumber: 1, //初始化加载第一页，默认第一页
    pagination: true,//是否分页
    queryParamsType: 'limit',//查询参数组织方式
    queryParams: queryParams,//请求服务器时所传的参数
    sidePagination: 'server',//指定服务器端分页
    pageSize: 10,//单页记录数
    pageList: [5, 10, 20, 30],//分页步进值
    showRefresh: true,//刷新按钮
    // showColumns: true,
    clickToSelect: true,//是否启用点击选中行
    toolbarAlign: 'left', //工具栏对齐方式
    buttonsAlign: 'left',//按钮对齐方式
    toolbar: '#toolbar',//指定工作栏
    columns: [

        {
            title:'分配权限',
            //跳转页面
            formatter:formatManage
        },
        {
            title: '用户名',
            field: 'userName',
            //列数据格式化
            formatter: formatUserName
        },

       /* {
            title: '身份证号',
            formatter: formatCardId
        },*/
        {
            title: '手机号码',
            field: 'userMobile',
            //列数据格式化
            formatter: formatMobile
        },
        {
            title: '真实姓名',
            field: 'realName',
            //列数据格式化
            formatter: formatRealName
        },

        {
            title: '联系地址',
            //列数据格式化
           formatter: formatAddress
        },
        {
            title: '邮箱',
            field: 'userEmail',
            //列数据格式化
            formatter: formatUserEmail
        },
        {
            title: '用户类型',
            filed: 'userType',
            //列数据格式化
            formatter: formatUserType
        },

        {
            title:'拥有权限',
            formatter:formatPowerInfo
        },
        {
            title: '员工状态',
            field: 'userState',//字段名必须与数据库中的字段名一致
            //列数据格式化
            formatter: formatStatus
        },
        {
            title: '最后修改者',
            field: 'lastModifiedUser',
        },
        {
            title: '最后修改时间',
            field: 'lastModifiedTime',
            //列数据格式化
            formatter: formatDate
        },
     ],
    locale: 'zh-CN',//中文支持,
    responseHandler: function (res) {
        //在ajax获取到数据，渲染表格之前，修改数据源
        total = res.total || 0
        return res;
    },
    onRefresh: function (params) {
        if (params && params.query) {
            return false;
        }
        $("#search-name").val('');
        $("#search-phone-num").val('');
        $("#search-login-name").val('');
    }
});

function toDetail(id) {
   // window.location.href = "/csfy/static/manage-sys/coupon-detail.html?id=" + id
}
//三个参数，value代表该列的值 员工状态(离职0;在职:1)
function formatStatus(value, row, index) {
    var text = '-';
    if (row.userStatus == "1") {
        text = '在职';
    } else if (row.userStatus == "0") {
        text = '离职';
    }
    return `<span>${text}</span>`;
}

//用户类型 用户类型(0：UAMS管理员 1：华大员工 2：外包账号 3：外部用户)
function formatUserType(value,row,index){
    var text = '-';
    if (row.userType == "0") {
        text = 'UAMS管理员';
    } else if (row.userType == "1") {
        text = '华大员工';
    }else if(row.userType == "2"){
        text = '外包账号';
    }else if(row.userType == "3"){
        text = '外部用户';
    }
    return `<span>${text}</span>`;
}

//三个参数，value代表该列的值
function formatRealName(value, row, index) {
    var userRealName = row.realName;
    if(userRealName != null && userRealName != ""){
        if(userRealName.length >10){
            userRealName = userRealName.substr(0,8)+"...";
        }
    }else{
        userRealName = "-";
    }
    return userRealName;
    //return '<a class="link" href="javascript:toDetail(' + ('\'' + row.id + '\'') + ');">' + value + '</a>';
}

//三个参数，value代表该列的值
function formatUserName(value, row, index) {
    var userNameInfo = row.userName;
    if(userNameInfo == ""){
        userNameInfo = "-";
    }
    return userNameInfo;
 }

//展示手机号信息
function formatMobile(value, row, index) {
    var userMobileInfo = row.userMobile;
    if(userMobileInfo == ""){
        userMobileInfo = "-";
    }
    return userMobileInfo;
 }

 //展示邮箱信息
function formatUserEmail(value, row, index) {
    var userEmailInfo = row.userEmail;
    if(userEmailInfo == ""){
        userEmailInfo = "-";
    }
    return userEmailInfo;
}

//三个参数，value代表该列的值
function formatAddress(value, row, index) {
    var userAddrInfo = row.userAddr;
    if(userAddrInfo != null && userAddrInfo != ""){
        if(userAddrInfo.length >6){
            userAddrInfo = userAddrInfo.substr(0,6)+"...";
        }
    }else{
        userAddrInfo = "-";
    }
    return userAddrInfo;
}

//三个参数，value代表该列的值
function formatDate(value, row, index) {
    var time = Date.parse(value);
    var date = new Date(time);
    return date.pattern("yyyy-MM-dd HH:mm:ss")
//            return value.substring(0,value.length - 2);
}

//所属权限
function formatPowerInfo(value,row){
    var firstMenu = row.menuCodeFirst;
    var secondMenu = row.menuCodeSecond;
    var fMenuLsit=[];
    var sMenuList=[];
    if(firstMenu != null && firstMenu !="" ){
        fMenuLsit = firstMenu.split(",");
    }

    if(secondMenu !=null && secondMenu !=""){
        sMenuList = secondMenu.split(",");
    }

    //一级菜单
    var textCont="";
    for(var i in fMenuLsit){
        switch(fMenuLsit[i]){
            case "A0" :
                textCont += "民生免费券，";
                break;
            case "B0" :
                textCont += "送检单，";
                break;
            case "C0" :
                textCont += "检测结果查询，";
                break;
            case "D0" :
                textCont += "统计报表，";
                break;
            case "E0" :
                textCont += "权限分配";
                break;
        }

    }

    //二级菜单
    var sMenuDetails = [
        {typeId:'A1',typeName:'免费券代申请'},{typeId:'A2',typeName:'扫码枪扫码'},{typeId:'A3',typeName:'免费券查看'},
        {typeId:'A4',typeName:'免费券审核'},{typeId:'B1',typeName:'查看送检单'},{typeId:'B2',typeName:'编辑送检单'},
        {typeId:'B3',typeName:'删除送检单'},{typeId:'D1',typeName:'统计报表（总）'},{typeId:'D2',typeName:'免费券--区县统计级'},
        {typeId:'D3',typeName:'免费券--区县详情'},{typeId:'D4',typeName:'免费券--医院级'},{typeId:'D5',typeName:'免费券--医院级详情'}
    ];

    if(sMenuList != "" && sMenuList != null){
        for(var j in sMenuList){
            for(var x in sMenuDetails){
                if(sMenuList[j] == sMenuDetails[x].typeId){
                    textCont += sMenuDetails[x].typeName+"，";
                }
            }
        }
    }

    if(textCont != ""){
        textCont = textCont.substr(0,8)+"...";
    }
    return '<span class="powerInfo">'+ textCont + '</span>';
}

//分配权限
function formatManage(value,row,index){
    return '<a class="link" href="javascript:toManagePower(' + ('\'' + row.userId + '\'') + ');">分配权限</a>';
}
function toManagePower(id){
    //window.location.href = "/csfy/static/manage-sys/power-detail.html?id=" + id;
    callParent("分配权限","/csfy/static/manage-sys/power-detail.html?id=" + id);
}

//请求服务数据时所传参数
function queryParams(params) {
    var param = new Object();
    var name = $("#search-name").val();
    if (name != '') {
        param.realName = name;
    }
    var phonenum = $("#search-phone-num").val();

    if (phonenum != null && phonenum != '') {
        param.userMobile = phonenum;
    }
    var loginName = $("#search-login-name").val();
    if (loginName != null && loginName != '') {
        param.userName = loginName;
    }

    param.rows = params.limit;
    param.page = (params.offset + params.limit) / params.limit;

    return param;

}

//查询按钮事件
$('#search-btn').click(function () {
    var name = $("#search-name").val() || '';
    var phonenum = $("#search-phone-num").val() || '';
    var loginname = $("#search-login-name").val() || '';
    var query = {};

    if (name != '') {
        query.realName = name;
    }

    if (phonenum != '') {
        query.userMobile = phonenum;
    }

    if (loginname != '') {
        query.userName = loginname;
    }

    $('#mytab').bootstrapTable('refresh', { url: '/csfy/user/findAllUamsUser.do', query });
})
//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 280;
}

//添加用户权限
$("#btn_add").click(function () {
    callParent('添加用户权限','/csfy/static/manage-sys/power-add.html');
});

//开启转发功能
/*function startShare() {
    var isStart = confirm("您确定要开启转发功能吗？");

    if(isStart){
        //显示遮罩层
        $("#overlay").show();
        //updateAddTransmit.do
        $.ajax({
            url: '/csfy/user/openTranspond.do',
            method: 'POST',
            success: function (res) {
                //res的值1：开启成功，2：已经是开启状态，0：开启失败
                if (res == 1) {
                    //window.location.href = "/csfy/index.do"
                    alert("开启成功！");
                    //关闭遮罩层
                    $("#overlay").hide();

                    $("#btn_start").removeClass("btn-primary").addClass("btn-forbid").removeAttr("onclick");
                    $("#btn_end").removeClass("btn-forbid").addClass("btn-primary").attr("onclick","endShare()");
                    sessionStorage.setItem("powerInfo","true");
                    return true;
                }/!*else if(res == 2){
                alert("目前已是开启转发功能状态！");
                $("#btn_start").removeClass("btn-primary").addClass("btn-forbid").removeAttr("onclick");
                $("#btn_end").removeClass("btn-forbid").addClass("btn-primary").attr("onclick","endShare()");
                return true;
            }*!/else if(res == 0){
                    alert("开启失败，请稍后操作！");
                    return false;
                }
            }

        })
    }

};*/

//暂停转发功能
function endShare() {
    var isStart = confirm("您确定要暂停转发功能吗？");
    if(isStart) {
        //显示遮罩层
        $("#overlay").show();
        //updateCloseTransmit.do
        $.ajax({
            url: '/csfy/user/closeTranspond.do',
            method: 'POST',
            success: function (res) {
                if (res) {
                    //window.location.href = "/csfy/index.do"
                    alert("暂停成功！");
                    //关闭遮罩层
                    $("#overlay").hide();
                    $("#btn_end").removeClass("btn-primary").addClass("btn-forbid").removeAttr("onclick");
                    //$("#btn_start").removeClass("btn-forbid").addClass("btn-primary").attr("onclick", "startShare()");
                    //sessionStorage.setItem("powerInfo","false");
                    return true;
                } else if (!res) {
                    alert("暂停失败，请稍后操作！");
                    
                    return false;
                }
            }
        })
    }
};

//优惠券类型配置
$("#btn_coupon").click(function () {
    // /csfy/user/toCouponConfig.do
    callParent('优惠券类型配置', '/csfy/static/manage-sys/country-list.html');
});

function callParent(title,url) {
    // var menuName=parent.$('#tt').tabs('getSelected').panel('options').title;
    //如果存在，直接刷新页面
    if (parent.$('#tt').tabs('exists', title)) {
        parent.$('#tt').tabs('close', title);
        window.parent.addTab(title, url);
    } else {
        window.parent.addTab(title, url);
    }
}
